var express = require("express");
var router = express.Router();
const Mock = require('mockjs');
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Types;

const {
  commodityModel,
  orderModel,
  historyListModel,
  ReturnsModel
} = require("../model/order"); 
/* GET home page. */


router.get("/returns", async (req, res) => {

  const page = parseInt(req.query.page, 10) || 1;
  const pageSize = parseInt(req.query.pageSize, 10) || 5;

  // 计算分页起始位置
  const startIndex = (page - 1) * pageSize;
  const objlen = Object.keys(req.query.obj).length
  const objs = JSON.parse(req.query.obj)
  const fn = []
  if (objlen > 2) {
    if (objs.status) {
      console.log(objs.status)
      fn.push({ status: objs.status })
    }
    if (objs.createTime) {
      console.log(objs.status)
      fn.push({ createTime: objs.createTime })
    }
    if (objs.handleTime) {
      fn.push({ handleTime: objs.handleTime })
    }
    if (objs.id) {
      console.log(objs.id);
      fn.push({ id: objs.id })
    }
    if (objs.memberUsername) {
      fn.push({ memberUsername: objs.memberUsername })
    }

    console.log(fn);
    if (fn.length == 0) {
      const data = await ReturnsModel.find().skip(startIndex).limit(pageSize);
      const total = await ReturnsModel.find().count()

      res.send({ data: { data, total: total }, code: 200 })
    } else {
      const data = await ReturnsModel.find({ $and: fn }).skip(startIndex).limit(pageSize);
      const total = await ReturnsModel.find({ $and: fn }).count()

      res.send({ data: { data, total }, code: 200 })
    }

  } else {
    const data = await ReturnsModel.find().skip(startIndex).limit(pageSize);
    const total = await ReturnsModel.find().count()

    res.send({ data: { data, total: total }, code: 200 })
  }
  // 查询数据并进行分页

});

router.get("/getorder", async (req, res) => {
  const page = req.query.page;
  const limit = 5;
  const startIndex = (page - 1) * limit;
  const { status, SubmitTime, sourceType, orderType, number, receiverName } =
    req.query;

  console.log(SubmitTime);
  const dataList = [];
  if (status != "undefined") {
    dataList.push({ status: status });
  }
  // if (SubmitTime != 'undefined') {
  //   console.log(1)
  //   dataList.push({ SubmitTime: SubmitTime })
  // }else{
  //   console.log(2);
  // }
  if (sourceType != "undefined") {
    dataList.push({ sourceType: sourceType });
  }
  if (orderType != "undefined") {
    dataList.push({ orderType: orderType });
  }
  if (number != "undefined") {
    dataList.push({ number: number });
  }
  if (receiverName != "undefined") {
    dataList.push({ receiverName: receiverName });
  }


  if (dataList.length == 0) {
    const datas = await orderModel.find();
    const data = await orderModel.find().skip(startIndex).limit(limit);
    res.send({
      data: { data, count: datas.length },
    });
  } else {
    const datas = await orderModel.find();
    const data = await orderModel
      .find({ $and: dataList })
      .skip(startIndex)
      .limit(limit);
    res.send({
      data: { data, count: data.length },
    });
  }
});


router.get("/orderdateil", async (req, res) => {
  const { id } = req.query;

  try {
    const data = await orderModel.find({ _id: id });
    if (!data) {
      res.status(404).send('No data found');
    } else {
      const commodity = await commodityModel.find({
        _id: { $in: data[0].commodity },
      });
      const historyList = await historyListModel.find({
        _id: { $in: data[0].historyList },
      });
      res.send({
        data: {
          data, commodity,
          historyList
        },
        code: 200
      })
    }
  } catch (error) {
    res.status(500).send('Internal Server Error');
  };
})

//修改状态
router.put("/orderupdate", async (req, res) => {
  const { id, status } = req.body;
  if (status == 6) {
    const data = await orderModel.deleteMany({ _id: { $in: id } })
    res.send({
      code: 200,
      msg: "删除成功",
      data
    })
  } else {
    const data = await orderModel.updateMany({ _id: { $in: id } }, { status: status })
    console.log(data)

    res.send({
      code: 200,
      msg: "修改成功",
      data
    })
  }
  // res.send({code:200})

})
router.delete('/orderdelete', async (req, res) => {
  await orderModel.deleteMany({ _id: req.query.id })
  res.send({
    code: 200

  })
})
router.put('/ordercancel', async (req, res) => {
  const { id } = req.body
  if (id == undefined) {
    res.send({ code: 201 })
  } else {
    let data = await orderModel.updateOne({ _id: id }, { status: 5 })
    res.send({
      code: 200
    })
  }

})
router.put('/historyadd', async (req, res) => {
  const obj = req.body
  const newHistory = await historyListModel.create(obj.data);
  const order = await orderModel.findById(obj.id);
  // 将新创建的 history 记录的 _id 添加到订单的 historyList 数组中
  order.historyList.push(newHistory._id);

  // 保存更新后的订单
  await order.save();
  res.send({
    code: 200
  })

})
router.post('/rdel', async (req, res) => {
  const { obj } = req.body
  console.log(obj);
  await ReturnsModel.deleteMany({ _id: obj })
  res.send({ code: 200 })
})
router.get('/returnsdetaile', async (req, res) => {
  const { id } = req.query
  console.log(id);

  try {
    const data = await ReturnsModel.find({ _id: id })
    if (!data) {
      res.status(404).send('No data found');
    } else {

      res.send({
        data,
        code: 200
      })
    }
  } catch {
    res.status(500).send('Internal Server Error');
  }

})
router.put('/rts', async (req, res) => {
  const { id, status } = req.body
  const data = await ReturnsModel.updateOne({ _id: id }, { status: status })
  res.send({
    code: 200
  })
  // 将新创建的 history 记录的 _id 添加到订单的 historyList 数组中
})
module.exports = router;
